package com.sansecy.video;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.google.android.exoplayer2.SimpleExoPlayer;
import com.google.android.exoplayer2.util.DebugTextViewHelper;
import com.sansecy.base.Constant;
import com.sansecy.base.FullScreenUtils;
import com.sansecy.video.player.IPlayer;
import com.sansecy.video.player.PlayerUtil;
import com.sansecy.video.player.SimplePlayer;
import com.sansecy.video.player.SimpleVideoView;

public class PlayerActivity extends AppCompatActivity {
    private SimpleVideoView playerView;
    private IPlayer mPlayer;
    private String mUri;
    private PlayerActivity mActivity;
    private Handler mHandler = new Handler();
    private DebugTextViewHelper mDebugTextViewHelper;

    public static void start(Context context, String url) {
        Intent starter = new Intent(context, PlayerActivity.class);
        starter.putExtra(Constant.URL, url);
        context.startActivity(starter);
    }

    private static final String TAG = "PlayerActivity-App";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mActivity = this;
        mUri = getIntent().getStringExtra(Constant.URL);

        getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
                WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_player);
        getWindow().setBackgroundDrawable(new ColorDrawable(Color.BLACK));
        playerView = new SimpleVideoView(this);
        FrameLayout content = findViewById(R.id.content);
        content.addView(playerView);
//        playerView.setPlayer(player);
        mPlayer = new SimplePlayer(this, SimplePlayer.EXOPLAYER);
        playerView.setUri(mUri);
        playerView.setPlayer(mPlayer);
        playerView.setTitle(mUri);

        mPlayer.setOnCompletionListener(new IPlayer.OnCompletionListener() {
            @Override
            public void onCompletion() {
                Log.d(TAG, "onCompletion() called");
                mHandler.removeCallbacks(mSavePlayPositionTask);
                PlayerUtil.savePlayPosition(mActivity, mUri, 0);
                PlayerUtil.savePlayDuration(mActivity, mUri, mPlayer.getDuration());
                finish();
            }
        });
        mPlayer.setOnErrorListener(new IPlayer.onErrorListener() {
            @Override
            public void onError(int unsupportedTracksType) {
                if (unsupportedTracksType == IPlayer.UNSUPPORTED_VIDEO_TRACKS) {
                    Toast.makeText(mActivity, "当前视频无法播放", Toast.LENGTH_SHORT).show();
                } else if (unsupportedTracksType == IPlayer.UNSUPPORTED_AUDIO_TRACKS) {
                    Toast.makeText(mActivity, "当前音频无法播放", Toast.LENGTH_SHORT).show();
                } else if (unsupportedTracksType == IPlayer.UNSUPPORTED_TEXT_TRACKS) {
                    Toast.makeText(mActivity, "当前字幕无法播放", Toast.LENGTH_SHORT).show();
                }
            }
        });
        TextView debugTextView = new TextView(this);
        debugTextView.setBackgroundColor(Color.BLACK);
        debugTextView.setTextColor(Color.WHITE);
        ViewGroup decorView = (ViewGroup) getWindow().getDecorView();
        decorView.addView(debugTextView, new FrameLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        mDebugTextViewHelper = new DebugTextViewHelper((SimpleExoPlayer) mPlayer.getPlayer(), debugTextView);
        if (!TextUtils.isEmpty(mUri)) {
            playVideo(mUri);
        }
    }

    Runnable mSavePlayPositionTask = new Runnable() {
        @Override
        public void run() {
            mHandler.removeCallbacks(mSavePlayPositionTask);
            PlayerUtil.savePlayPosition(mActivity, mUri, mPlayer.getCurrentPosition());
            PlayerUtil.savePlayDuration(mActivity, mUri, mPlayer.getDuration());
            mHandler.postDelayed(this, 500);
        }
    };

//    @Override
//    public boolean dispatchTouchEvent(MotionEvent ev) {
//        return mTrainVolumeBrightnessController.onActivityTouchEvent(ev) || super.dispatchTouchEvent(ev);
//    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus) {
            FullScreenUtils.setStickFullScreen(getWindow().getDecorView());
        }
    }

    private void playVideo(String videoUri) {
        mPlayer.setUri(Uri.parse(videoUri));
//        PlayerUtil.seekTo(this, mPlayer, mUri);
        mHandler.post(mSavePlayPositionTask);
        mPlayer.start();
//        mDebugTextViewHelper.start();
    }

    private void playVideo(String videoUri, String subtitleUrl) {
        mPlayer.setUri(Uri.parse(videoUri), subtitleUrl);
//        PlayerUtil.seekTo(this, mPlayer, mUri);
        mHandler.post(mSavePlayPositionTask);
        mPlayer.start();
//        mDebugTextViewHelper.start();
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (mPlayer.getDuration() > 0) {
            mPlayer.start();
            mHandler.post(mSavePlayPositionTask);
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        PlayerUtil.savePlayPosition(this, mUri, mPlayer.getCurrentPosition());
        mPlayer.pause();
        mHandler.removeCallbacks(mSavePlayPositionTask);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mPlayer.release();
        mDebugTextViewHelper.stop();
    }
}
